package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.woyao.core.model.GetSearchResponse;
import com.woyao.core.model.SearchItem;
import com.woyao.core.model.SearchResult;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class SearchActivity extends AppCompatActivity {
    ProgressDialog progressDialog;

    String keyword ="";

    private SearchView mSearchView;


    LinearLayout personArea;
    private List<SearchItem> personItems = new ArrayList<SearchItem>();
    private SearchAdapter personAdapter;
    private RecyclerView personList = null;
    LinearLayoutManager personLayoutManager = null;


    LinearLayout chanceArea;
    private List<SearchItem> chanceItems = new ArrayList<SearchItem>();
    private SearchAdapter chanceAdapter;
    private RecyclerView chanceList = null;
    LinearLayoutManager chanceLayoutManager = null;

    LinearLayout orgArea;
    private List<SearchItem> orgItems = new ArrayList<SearchItem>();
    private SearchAdapter orgAdapter;
    private RecyclerView orgList = null;
    LinearLayoutManager orgLayoutManager = null;

    TextView personBtn;
    TextView chanceBtn;
    TextView orgBtn;

    TextView personSummary;
    TextView chanceSummary;
    TextView orgSummary;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        Toolbar toolbar = (Toolbar) findViewById(R.id.invite_toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        personArea = ( LinearLayout )findViewById(R.id.search_persons_area);
        personList = (RecyclerView)findViewById(R.id.search_persons);
        personLayoutManager = new LinearLayoutManager(SearchActivity.this);
        personLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        personList.setLayoutManager(personLayoutManager);
        personList.addItemDecoration(new DividerItemDecoration(SearchActivity.this, DividerItemDecoration.VERTICAL_LIST));


        orgArea = ( LinearLayout )findViewById(R.id.search_org_area);
        orgList = (RecyclerView)findViewById(R.id.search_orgs);
        orgLayoutManager = new LinearLayoutManager(SearchActivity.this);
        orgLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        orgList.setLayoutManager(orgLayoutManager);
        orgList.addItemDecoration(new DividerItemDecoration(SearchActivity.this, DividerItemDecoration.VERTICAL_LIST));

        chanceArea = ( LinearLayout )findViewById(R.id.search_chances_area);
        chanceList = (RecyclerView)findViewById(R.id.search_chances);
        chanceLayoutManager = new LinearLayoutManager(SearchActivity.this);
        chanceLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        chanceList.setLayoutManager(chanceLayoutManager);
        chanceList.addItemDecoration(new DividerItemDecoration(SearchActivity.this, DividerItemDecoration.VERTICAL_LIST));

        personSummary = (TextView)findViewById(R.id.search_persons_summary);
        chanceSummary = (TextView)findViewById(R.id.search_chances_summary);
        orgSummary = (TextView)findViewById(R.id.search_orgs_summary);

        personBtn = (TextView)findViewById(R.id.search_persons_more);
        personBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search( mSearchView.getQuery().toString(),"person");
            }
        });


        chanceBtn = (TextView)findViewById(R.id.search_chances_more);
        chanceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search( mSearchView.getQuery().toString(),"chance");
            }
        });



        orgBtn = (TextView)findViewById(R.id.search_orgs_more);
        orgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search( mSearchView.getQuery().toString(),"org");
            }
        });


        mSearchView = (SearchView) findViewById(R.id.id_search_content);
//        mSearchView.setVisibility(View.GONE);
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                search(query,"");
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

        Button finishBtn  = (Button) findViewById(R.id.id_search_finish);
        finishBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });



        personArea.setVisibility(View.GONE);
        chanceArea.setVisibility(View.GONE);
        orgArea.setVisibility(View.GONE);

        Intent intent = getIntent();
        keyword = intent.getStringExtra("keyword");


        if (keyword != null){
            search( keyword,"");
            mSearchView.setVisibility(View.GONE);
        }else {

            mSearchView.requestFocus();
        }

    }



    public void search( final String kw,final String type ){
        progressDialog = new ProgressDialog(SearchActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在处理···");
        progressDialog.show();

        AsyncTask<Void,Void, GetSearchResponse> task1 =new AsyncTask<Void, Void, GetSearchResponse>() {
            @Override
            protected GetSearchResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetSearchResponse> responseCall = svc.search(userId,type,kw);
                try {
                    GetSearchResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetSearchResponse response) {
                progressDialog.dismiss();
                if (response.isSuccess()) {
                    render(response);
                }else{
                    Dialog alertDialog = new AlertDialog.Builder(SearchActivity.this).
                            setTitle("信息").
                            setMessage(response.getMessage()).
                            setIcon(R.drawable.ic_launcher).
                            setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if ( response.getCondition().equals("charge")){
                                        renderMoney( );
                                    }

                                }
                            }).
                            setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).
                            create();
                    alertDialog.show();
                }

            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task1.execute((Void)null);
    }

    private void renderMoney( ){

        Intent intent = new Intent();
        intent.putExtra("money", 100.0);
        intent.setClass(SearchActivity.this, MoneyActivity.class);
        startActivity(intent);
    }
    private void render(GetSearchResponse response){
        SearchResult sr = response.getContent();


        if (sr.getChances().size() > 0 ) {
            chanceItems = sr.getChances();

            chanceAdapter = new SearchAdapter(SearchActivity.this, chanceItems,"chance");

            chanceAdapter.setChangedHandler(new SearchAdapter.Changed() {
                @Override
                public void view(SearchItem cs) {
                    if (cs.getId() > 0) {
                        Intent intent = new Intent();
                        intent.setClass(SearchActivity.this, ChanceViewActivity.class);
                        intent.putExtra("id", cs.getId());   //bid
                        startActivity(intent);
                    }else{
//                        Common.alert(SearchActivity.this,"该用户未注册");
                    }
                }

                @Override
                public void act(SearchItem cs) {

                }
            });

            chanceList.setAdapter(chanceAdapter);
            chanceBtn.setVisibility(View.VISIBLE);
            chanceArea.setVisibility(View.VISIBLE);

        }else{
            chanceArea.setVisibility(View.GONE);
        }
        chanceSummary.setText( sr.getChances_summary());

        if (sr.getPersons().size() > 0 ) {
            personItems = sr.getPersons();

            personAdapter = new SearchAdapter(SearchActivity.this, personItems,"person");

            personAdapter.setChangedHandler(new SearchAdapter.Changed() {
                @Override
                public void view(SearchItem cs) {
                    if (cs.getId() > 0) {
                        Intent intent = new Intent();
                        intent.setClass(SearchActivity.this, PersonViewActivity.class);
                        intent.putExtra("id", cs.getId());
                        startActivity(intent);
                    }else{
//                        Common.alert(SearchActivity.this,"该用户未注册");
                    }
                }

                @Override
                public void act(SearchItem cs) {

                }
            });

            personList.setAdapter(personAdapter);
            personBtn.setVisibility(View.VISIBLE);
            personArea.setVisibility(View.VISIBLE);

        }else{
            personArea.setVisibility(View.GONE);
        }
        personSummary.setText( sr.getPersons_summary());

        if (sr.getOrgs().size() > 0 ) {
            orgItems = sr.getOrgs();

            orgAdapter = new SearchAdapter(SearchActivity.this, orgItems,"org");

            orgAdapter.setChangedHandler(new SearchAdapter.Changed() {
                @Override
                public void view(SearchItem cs) {
                    if (cs.getId() > 0) {
                        Intent intent = new Intent();
                        intent.setClass(SearchActivity.this, OrgViewActivity.class);
                        intent.putExtra("id", cs.getId() );
                        startActivity(intent);
                    }else{
//                        Common.alert(SearchActivity.this,"该用户未注册");
                    }
                }

                @Override
                public void act(SearchItem cs) {

                }
            });

            orgList.setAdapter(orgAdapter);
            orgBtn.setVisibility(View.VISIBLE);
            orgArea.setVisibility(View.VISIBLE);
        }else{
            orgArea.setVisibility(View.GONE);
        }
        orgSummary.setText(sr.getOrgs_summary());

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }





}
